package cn.corgy.module.loadbalance.impl;

import cn.corgy.dto.RpcRequest;
import cn.corgy.module.loadbalance.AbstractLoadBalance;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PollingLoadBalance extends AbstractLoadBalance {
    private final AtomicInteger integer = new AtomicInteger(0);

    @Override
    protected String doSelect(List<String> serviceAddresses, RpcRequest rpcRequest) {
        return polling(serviceAddresses);
    }


    /**
     * 简单的demo 实现列字符的轮询显示
     *
     * @param list 需要轮询的列表
     * @return Str
     */
    public String polling(List<String> list) {
        //先获取列表的长度
        int size = list.size();
        //简单的实现自旋锁
        for (; ; ) {
            int cur = integer.get();
            int next = (cur + 1) % size;
            if (integer.compareAndSet(cur, next)) return list.get(next);
        }
    }
}


